package org.demo.net.qsee;

import net.sourceforge.jpcap.capture.PacketCapture;
import net.sourceforge.jpcap.capture.PacketListener;

/**
 * 
 * @author  
 * @date    2010-11-7
 * @file    org.demo.net.qsee.PacketCapture.java
 */
public class QPacketCapture {
	/**
	 * For Testing
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args)throws Exception {
		final QPacketCapture cap = new QPacketCapture();		
		cap.start();
	}
	
	private PacketCapture _pcap;
	private String[] devices;
	private String current_device;
	private String filter = "";
	private PacketListener objListener = new UDPPacketListener();	
	private int packet_count = -1;
	/**
	 * Constructor Method
	 */
	public QPacketCapture() throws Exception{
		// Step 1: Instantiate Capturing Engine
		_pcap = new PacketCapture();
		
		// Step 2: Check for devices
		// get all devices
		devices = PacketCapture.lookupDevices();
		// There should delete everything after a '\n'
		int idx = -1;
		for (int i=0; i<devices.length; i++){
			idx = devices[i].indexOf('\n');
			if (idx != -1){
				devices[i] = devices[i].substring(0,idx);
			}
		}
		// get current device
		current_device = _pcap.findDevice();
		idx = current_device.indexOf('\n');
		if (idx != -1){
			current_device = current_device.substring(0,idx);
		}		
	}	
	/**
	 * @param packetCount the packet_count to set
	 */
	public void setPacket_count(int packetCount) {
		packet_count = packetCount;
	}
	/**
	 * Start capturing packets
	 * @throws Exception
	 */
	public void start() throws Exception{
		// Open device for Capturing
		_pcap.open(current_device, true);
		// Add a BPF Filter
		_pcap.setFilter(filter, true);
		// Register a Listener for Packets
		if (objListener != null){
			_pcap.addPacketListener(objListener);
		}		
		// Capture Data
		_pcap.capture(packet_count);
	}
}
